package com.platform.api.bzproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.api.bzproject.dao.BzDeductionMapper;
import com.platform.api.bzproject.model.BzDeduction;
import com.platform.api.bzproject.model.BzDeductionRecord;
import com.platform.api.bzproject.dao.BzDeductionRecordMapper;
import com.platform.api.bzproject.service.IBalanceRecordService;
import com.platform.api.bzproject.service.IBzDeductionRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.api.bzproject.service.IDistributionProfitService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 扣量记录表 服务实现类
 * </p>
 *
 * @author guoshao
 * @since 2022-02-23
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class BzDeductionRecordServiceImpl extends ServiceImpl<BzDeductionRecordMapper, BzDeductionRecord> implements IBzDeductionRecordService {

    @Autowired
    private BzDeductionRecordMapper bzDeductionRecordMapper;

    @Autowired
    private BzDeductionMapper bzDeductionMapper;

    @Autowired
    private IBalanceRecordService iBalanceRecordService;

    @Autowired
    private IDistributionProfitService iDistributionProfitService;

    /**
     * 获取当前用户扣量信息
     * @param userId
     * @return
     */
    @Override
    public BzDeductionRecord getBzDeductionRecordByUserId(String userId) {
        return bzDeductionRecordMapper.getBzDeductionRecordByUserId(userId);
    }

    /**
     * 保存或修改扣量信息记录
     * @param parentId 上级用户ID
     * @param userId 用户ID
     * @param deCount 扣量数
     * @param isAdd 是否add
     * @return
     */
    @Override
    public int saveOrUpdateDeductionRecord(String parentId,String userId, int deCount,boolean isAdd) {
        BzDeductionRecord record= bzDeductionRecordMapper.getBzDeductionRecordByUserId(userId);
        if(null != record) {
            //获取当日下载的记录数,此处直接+1
            record.setSumCount(isAdd ? record.getSumCount() + 1 : record.getSumCount());
            record.setDeCount(deCount + record.getDeCount());
            return bzDeductionRecordMapper.updateById(record);
        }
        BzDeductionRecord deductionRecord = new BzDeductionRecord();
        deductionRecord.setDeCount(0);
        deductionRecord.setSumCount(1);
        deductionRecord.setDeTime(new Date());
        deductionRecord.setUserId(userId);
        deductionRecord.setParentId(parentId);
        return bzDeductionRecordMapper.insert(deductionRecord);
    }


    /**
     * 扣量
     * @param userId 用户ID
     * @param parentUserId 上级用户
     * @param appid 小程序APPID
     */
    @Override
    public boolean deduction(String userId,String parentUserId,String appid){

        //查询扣量信息
        BzDeductionRecord record = getBzDeductionRecordByUserId(userId);
        if(null == record){
            return false;
        }

        //当日广告总数
        int sumCount = record.getSumCount();

        //获取扣量信息
        List<BzDeduction> list = bzDeductionMapper.selectList(new QueryWrapper<BzDeduction>().eq("appid", appid)
        .eq("status",1));

        //遍历扣量信息，验证此用户的广告下载量是否超过设置的
        for (BzDeduction du : list){
            //广告次数超过设定的量
            if(sumCount >= du.getStartCount().intValue() && sumCount <= du.getEndCount().intValue()){

                //未配置扣除基数-跳出当前循环
                if(StringUtils.isEmpty(du.getRatioBase())){
                    continue;
                }

                int yushu = sumCount % 10;

                if(yushu != 0){
                    // 余数不为0时，跳出循环
                    break;
                }

                //获取配置的扣量基数
                String[] bases = du.getRatioBase().split("/");

                if(bases.length > 0){
                    //随机获取数组的下标
                    Random input2=new Random();
                    int index = input2.nextInt(bases.length);

                    //扣量数量
                    Integer deCount = Integer.valueOf(bases[index]);
                    System.out.println(Integer.valueOf(bases[index]) +" ======");
                    //删除当前壁纸所属用户的收益
                    iBalanceRecordService.delRandId(userId,deCount);
                    //删除当前壁纸所属用户的上级分销数据
                    iDistributionProfitService.delRandId(parentUserId,userId,deCount);

                    //设置扣量信息
                    saveOrUpdateDeductionRecord(null,userId,deCount,false);
                    return true;
                }

            }

        }
        return false;
    }

}
